package com.ice.app.project.generator.service;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ice.app.project.generator.utils.GeneratorUtils;
import com.ice.app.project.mapper.GeneratorMapper;

@Service
public class GeneratorService {

	@Autowired
	private GeneratorMapper generatorMapper;

	/**
	 * 查询数据列表
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getTableAttribute(String tableName) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("tableName", tableName);
		return generatorMapper.selectByFilter(map);
	}

	/**
	 * 查询表信息
	 * @param tableName
	 * @return
	 */
	public Map<String, String> queryTable(String tableName) {
		return generatorMapper.queryTable(tableName);
	}

	/**
	 * 查询列信息
	 * @param tableName
	 * @return
	 */
	public List<Map<String, String>> queryColumns(String tableName) {
		return generatorMapper.queryColumns(tableName);
	}

	public byte[] generatorCode(String[] tableNames) throws Exception {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		for (String tableName : tableNames) {
			// 查询表信息
			Map<String, String> table = queryTable(tableName);
			// 查询列信息
			List<Map<String, String>> columns = queryColumns(tableName);
			// 生成代码
			GeneratorUtils.generatorCode(table, columns, zip);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}
}
